<template>
    <div class="default-main">
        <div class="banner">
            <el-row :gutter="10">
                <el-col :md="24" :lg="18">
                    <div class="welcome">
                        <img class="welcome-img" :src="headerSvg" alt="" />
                        <div class="welcome-text">
                            <div class="welcome-title">{{ adminInfo.nickname + t('utils.comma') + getGreet() }}</div>
                            <div class="welcome-note"></div>
                        </div>
                    </div>
                </el-col>
                <el-col :lg="6" class="hidden-md-and-down">
                    <div class="working">
                        <img class="working-coffee" :src="coffeeSvg" alt="" />
                        <div class="working-text">
                            {{ t('shop.dashboard.You have worked today') }}<span class="time">{{ state.workingTimeFormat }}</span>
                        </div>
                        <div @click="onChangeWorkState()" class="working-opt working-rest">
                            {{ state.pauseWork ? t('shop.dashboard.Continue to work') : t('shop.dashboard.have a bit of rest') }}
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <div class="small-panel-box">
            <el-row :gutter="24">
                <!--                <el-col :sm="12" :lg="computedLg">-->
                <!--                    <router-link-->
                <!--                        :to="`${adminBaseRoutePath}/shop/order/order?status=${orderStatusEnum.toShipped}`"-->
                <!--                        class="small-panel link-block suspension"-->
                <!--                    >-->
                <!--                        <div class="small-panel-title">{{ '待发货' }}</div>-->
                <!--                        <div class="small-panel-content">-->
                <!--                            <div class="content-left">-->
                <!--                                <Icon color="#8595F4" size="25" name="fa fa-truck" />-->
                <!--                                <span id="to_shipped_count">{{ state.boardData.to_shipped_count }}</span>-->
                <!--                            </div>-->
                <!--                        </div>-->
                <!--                    </router-link>-->
                <!--                </el-col>-->
                <!--                <el-col :sm="12" :lg="computedLg">-->
                <!--                    <router-link-->
                <!--                        :to="`${adminBaseRoutePath}/shop/order/order?status=${orderStatusEnum.applyCancel}`"-->
                <!--                        class="small-panel link-block suspension"-->
                <!--                    >-->
                <!--                        <div class="small-panel-title">{{ '退款待审核' }}</div>-->
                <!--                        <div class="small-panel-content">-->
                <!--                            <div class="content-left">-->
                <!--                                <Icon color="#8595F4" size="20" name="fa fa-credit-card-alt" />-->
                <!--                                <span id="cancel_count"> {{ state.boardData.cancel_count }}</span>-->
                <!--                            </div>-->
                <!--                        </div>-->
                <!--                    </router-link>-->
                <!--                </el-col>-->
                <!--                <el-col :sm="12" :lg="computedLg">-->
                <!--                    <router-link-->
                <!--                        :to="`${adminBaseRoutePath}/shop/order/refund?audit_status=${auditStatus.wait_audit}`"-->
                <!--                        class="small-panel link-block suspension"-->
                <!--                    >-->
                <!--                        <div class="small-panel-title">{{ '售后待审核' }}</div>-->
                <!--                        <div class="small-panel-content">-->
                <!--                            <div class="content-left">-->
                <!--                                <Icon color="#8595F4" size="25" name="el-icon-Checked" />-->
                <!--                                <span id="refund_audit_count">{{ state.boardData.refund_audit_count }}</span>-->
                <!--                            </div>-->
                <!--                        </div>-->
                <!--                    </router-link>-->
                <!--                </el-col>-->
                <el-col :sm="12" :lg="computedLg">
                    <!--                    <router-link class="small-panel link-block suspension" :to="`${adminBaseRoutePath}/shop/goods/goods?status=1&total_stock=0,10`">-->
                    <!--                        <div class="small-panel-title" style="display: inline-flex; align-items: center">-->
                    <!--                            {{ '库存预警' }}-->
                    <!--                            <el-tooltip effect="dark" content="上架中且库存低于10的商品" placement="top">-->
                    <!--                                <el-icon style="margin-left: 4px" :size="12">-->
                    <!--                                    <Icon name="el-icon-Warning" size="14" />-->
                    <!--                                </el-icon>-->
                    <!--                            </el-tooltip>-->
                    <!--                        </div>-->
                    <!--                        <div class="small-panel-content">-->
                    <!--                            <div class="content-left">-->
                    <!--                                <Icon color="#8595F4" size="20" name="fa fa-exclamation-triangle" />-->
                    <!--                                <span id="stock_alert_count">{{ state.boardData.stock_alert_count }}</span>-->
                    <!--                            </div>-->
                    <!--                        </div>-->
                    <!--                    </router-link>-->
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :sm="12" :lg="computedLg" v-for="(item, key) in state.orderData" :key="key">
                    <div class="small-panel">
                        <div class="small-panel-title">{{ item.label }}</div>
                        <div class="small-panel-content">
                            <div class="content-left">
                                <Icon color="#8595F4" size="26" name="el-icon-List" />
                                <span :id="'order_data_statistics_' + key"> {{ item.value }} </span>
                            </div>
                            <div style="" class="content-bottom">
                                <div class="compare">
                                    {{ item.compareLabel }}
                                    <el-text
                                        class="compare-text"
                                        :id="'order_data_statistics_compare_' + key"
                                        :class="getIconClass(item.compareValue)"
                                    >
                                        {{ item.compareValue }}
                                    </el-text>
                                    <Icon name="el-icon-CaretBottom" size="14" v-if="Number(item.compareValue) < 0" style="color: green" />
                                    <Icon name="el-icon-CaretTop" size="14" v-if="Number(item.compareValue) > 0" style="color: red" />
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :sm="12" :lg="computedLg" v-for="(item, key) in state.orderSaleData" :key="key">
                    <div class="small-panel">
                        <div class="small-panel-title">{{ item.label }}</div>
                        <div class="small-panel-content">
                            <div class="content-left">
                                <Icon color="#8595F4" size="26" name="fa fa-cny" />
                                <span :id="'order_sales_statistics_' + key">{{ item.value }} </span>
                            </div>
                            <div style="" class="content-bottom">
                                <div class="compare">
                                    {{ item.compareLabel }}
                                    <el-text
                                        :id="'order_sales_statistics_compare_' + key"
                                        :class="getIconClass(item.compareValue)"
                                        class="compare-text"
                                    >
                                        {{ item.compareValue }}
                                    </el-text>
                                    <Icon name="el-icon-CaretBottom" size="14" v-if="Number(item.compareValue) < 0" style="color: green" />
                                    <Icon name="el-icon-CaretTop" size="14" v-if="Number(item.compareValue) > 0" style="color: red" />
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>

            <el-row :gutter="24">
                <el-col :sm="12" :lg="computedLg" v-for="(item, key) in state.userData" :key="key">
                    <div class="small-panel">
                        <div class="small-panel-title">{{ item.label }}</div>
                        <div class="small-panel-content">
                            <div class="content-left">
                                <Icon color="#8595F4" size="26" name="fa fa-user" />
                                <span :id="'user_data_statistics_' + key">{{ item.value }} </span>
                            </div>
                            <div style="" class="content-bottom">
                                <div class="compare">
                                    {{ item.compareLabel }}
                                    <el-text
                                        :id="'user_data_statistics__compare_' + key"
                                        :class="getIconClass(item.compareValue)"
                                        class="compare-text"
                                    >
                                        {{ item.compareValue }}
                                    </el-text>
                                    <Icon name="el-icon-CaretBottom" size="14" v-if="Number(item.compareValue) < 0" style="color: green" />
                                    <Icon name="el-icon-CaretTop" size="14" v-if="Number(item.compareValue) > 0" style="color: red" />
                                </div>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <div class="growth-chart">
            <el-row :gutter="20">
                <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="24">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="statistic-chart-header">
                                <div>
                                    <Icon name="fa fa-line-chart" />
                                    <span>订单销售数据</span>
                                </div>
                                <div>
                                    <el-date-picker
                                        style="margin-left: 45px"
                                        v-model="orderStatisticsChartTimeRange"
                                        type="datetimerange"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        range-separator="至"
                                        format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                        :shortcuts="shortcuts"
                                        :default-time="[new Date().setHours(0, 0, 0), new Date().setHours(23, 59, 59)]"
                                        @change="onChangeOrderStatisticsChartTime"
                                    />
                                </div>
                            </div>
                        </template>
                        <div class="order-statistics-chart" ref="orderStatisticsChartRef"></div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <div class="growth-chart">
            <el-row :gutter="20">
                <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="24">
                    <el-card shadow="hover">
                        <template #header>
                            <div class="statistic-chart-header">
                                <div>
                                    <Icon name="fa fa-line-chart" />
                                    <span>用户注册数据</span>
                                </div>
                                <div>
                                    <el-date-picker
                                        style="margin-left: 45px"
                                        v-model="userStatisticsChartTimeRange"
                                        type="datetimerange"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        range-separator="至"
                                        format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss"
                                        :shortcuts="shortcuts"
                                        :default-time="[new Date().setHours(0, 0, 0), new Date().setHours(23, 59, 59)]"
                                        @change="onChangeUserStatisticsChartTime"
                                    />
                                </div>
                            </div>
                        </template>
                        <div class="user-statistics-chart" ref="userStatisticsChartRef"></div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

        <!--        <div class="growth-chart">-->
        <!--            <el-row :gutter="20">-->
        <!--                <el-col :xs="24" :sm="24" :md="24" :lg="12" style="padding-bottom: 20px">-->
        <!--                    <el-card shadow="hover">-->
        <!--                        <template #header>-->
        <!--                            <div class="statistic-chart-header">-->
        <!--                                <div>-->
        <!--                                    <Icon name="el-icon-Sell" />-->
        <!--                                    <span>商品销售数据 </span>-->
        <!--                                </div>-->
        <!--                            </div>-->
        <!--                        </template>-->
        <!--                        <div class="goods-sale-rank-chart">-->
        <!--                            <el-table :data="state.goodsSaleData" max-height="200" table-layout="fixed">-->
        <!--                                <el-table-column label="排名" type="index" width="80" align="center"></el-table-column>-->
        <!--                                <el-table-column label="商品名称" prop="goods_name" :show-overflow-tooltip="true" align="center"></el-table-column>-->
        <!--                                <el-table-column label="销量(件)" prop="sale_volume" width="100" align="center" sortable></el-table-column>-->
        <!--                                <el-table-column label="销售额(元)" prop="sale_values" width="120" align="center" sortable></el-table-column>-->
        <!--                            </el-table>-->
        <!--                        </div>-->
        <!--                    </el-card>-->
        <!--                </el-col>-->
        <!--                <el-col class="lg-mb-20" :xs="24" :sm="24" :md="24" :lg="12">-->
        <!--                    <el-card shadow="hover">-->
        <!--                        <template #header>-->
        <!--                            <div class="statistic-chart-header">-->
        <!--                                <div>-->
        <!--                                    <Icon name="el-icon-PieChart" />-->
        <!--                                    <span>用户消费数据 </span>-->
        <!--                                </div>-->
        <!--                            </div>-->
        <!--                        </template>-->
        <!--                        <div class="user-consume-ratio-chart" ref="userConsumeRatioChartRef"></div>-->
        <!--                    </el-card>-->
        <!--                </el-col>-->
        <!--            </el-row>-->
        <!--        </div>-->
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, nextTick, onActivated, watch, onBeforeMount, onBeforeUpdate, ref } from 'vue'
import headerSvg from '/src/assets/dashboard/header-1.svg'
import coffeeSvg from '/src/assets/dashboard/coffee.svg'
import { CountUp } from 'countup.js'
import * as echarts from 'echarts'
import { useNavTabs } from '/src/stores/navTabs'
import { index, getStatisticsChart } from '/src/api/backend/shop/dashboard'
import { useI18n } from 'vue-i18n'
import { Local } from '/src/utils/storage'
import { useAdminInfo } from '/src/stores/adminInfo'
import { WORKING_TIME } from '/src/stores/constant/cacheKey'
import { getGreet } from '/src/utils/common'
import { useEventListener } from '@vueuse/core'
import { adminBaseRoutePath } from '/src/router/static/adminBase'
import { orderStatusEnum } from './order/order'
import { auditStatus } from './order/refund'
import { getFirstDayOfMonth, getFirstDayOfWeek } from '/src/utils/shop/datetime'

let workTimer: number

defineOptions({
    name: 'dashboard',
})

const d = new Date()
const { t } = useI18n()
const navTabs = useNavTabs()
const adminInfo = useAdminInfo()
const computedLg = ref(6)

type statisticsItem = {
    label: string
    value: number
    compareLabel: string
    compareValue: string
    totalSale: string
}
type orderChartItem = {
    time: string
    total: string
    totalSale: string
}
type userChartItem = {
    time: string
    total: string
}
type ratioChart = {
    name: string
    value: string
}
type boardItem = {
    cancel_count: number
    refund_audit_count: number
    to_shipped_count: number
    stock_alert_count: number
}
const state: {
    charts: any[]
    remark: string
    workingTimeFormat: string
    pauseWork: boolean
    boardData: boardItem
    orderData: statisticsItem[]
    orderSaleData: statisticsItem[]
    userData: statisticsItem[]
    orderStatisticsChartId: string
    orderStatisticsChart: orderChartItem[]
    userStatisticsChartId: string
    userStatisticsChart: userChartItem[]
    userConsumeRatioData: ratioChart[]
    goodsSaleData: ratioChart[]
} = reactive({
    charts: [],
    remark: 'dashboard.Loading',
    workingTimeFormat: '',
    pauseWork: false,
    boardData: {
        cancel_count: 0,
        refund_audit_count: 0,
        to_shipped_count: 0,
        stock_alert_count: 0,
    },
    orderData: [],
    orderSaleData: [],
    userData: [],
    orderStatisticsChartId: '',
    orderStatisticsChart: [],
    userStatisticsChartId: '',
    userStatisticsChart: [],
    userConsumeRatioData: [],
    goodsSaleData: [],
})

const getIconClass = (value: string) => {
    const num = Number(value)
    if (num == 0 || isNaN(num)) {
        return ''
    }
    return num > 0 ? 'red' : 'green'
}

const countUpFun = (id: string, countupOption?: any) => {
    nextTick(() => {
        let value = document.getElementById(id)?.innerText

        let options = {
            startVal: 0,
            duration: 1.5,
            useGrouping: false,
        }
        if (countupOption) {
            options = Object.assign(options, countupOption)
        }
        if (value) {
            if (/^-?\d*\.?\d+$/.test(value)) {
                new CountUp(id, parseFloat(value), options).start()
            } else {
                return value
            }
        }
    })
}

const initCountUp = () => {
    for (const key in state.boardData) {
        countUpFun(key)
    }
    for (const key in state.orderData) {
        countUpFun('order_data_statistics_' + key)
        countUpFun('order_data_statistics_compare_' + key, {
            decimalPlaces: 2,
            suffix: '%',
        })
    }
    for (const key in state.orderSaleData) {
        countUpFun('order_sales_statistics_' + key, {
            decimalPlaces: 2,
        })
        countUpFun('order_sales_statistics_compare_' + key, {
            decimalPlaces: 2,
            suffix: '%',
        })
    }
    for (const key in state.userData) {
        countUpFun('user_data_statistics_' + key)
        countUpFun('user_data_statistics__compare_' + key, {
            decimalPlaces: 2,
            suffix: '%',
        })
    }
}

const shortcuts = [
    {
        text: '昨天',
        value: () => {
            const today = new Date()

            const startDate = new Date(today)
            startDate.setDate(startDate.getDate() - 1)
            startDate.setHours(0, 0, 0)

            const endDate = new Date(startDate)
            endDate.setHours(23, 59, 59)

            return [startDate, endDate]
        },
    },
    {
        text: '今天',
        value: () => {
            const today = new Date()
            const startDate = today.setHours(0, 0, 0)
            const endDate = today.setHours(23, 59, 59)

            return [startDate, endDate]
        },
    },
    {
        text: '上周',
        value: () => {
            const Monday = new Date(getFirstDayOfWeek())

            const lastMonday = Monday.setDate(Monday.getDate() - 7)
            const startDate = new Date(lastMonday).setHours(0, 0, 0)

            const endDate = new Date(new Date(lastMonday).setDate(Monday.getDate() + 6))
            endDate.setHours(23, 59, 59)

            return [startDate, endDate]
        },
    },
    {
        text: '本周',
        value: () => {
            const startDate = new Date(getFirstDayOfWeek())
            startDate.setHours(0, 0, 0)

            const endDate = new Date(new Date(startDate).setDate(startDate.getDate() + 6))
            endDate.setHours(23, 59, 59)

            return [startDate, endDate]
        },
    },
    {
        text: '上月',
        value: () => {
            const today = new Date()

            const startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1, 0, 0, 0)

            const endDate = new Date(today.getFullYear(), today.getMonth(), 0, 23, 59, 59)

            return [startDate, endDate]
        },
    },
    {
        text: '本月',
        value: () => {
            const startDate = new Date(getFirstDayOfMonth())
            startDate.setHours(0, 0, 0)

            const endDate = new Date(new Date().setMonth(startDate.getMonth()))
            endDate.setHours(23, 59, 59)

            return [startDate, endDate]
        },
    },
]

const orderStatisticsChartTimeRange = ref([])

const onChangeOrderStatisticsChartTime = (value: any[]) => {
    if (!value) return
    const [startTime, endTime] = value
    // 转化为时间戳
    getStatisticsChart({
        type: 'order',
        range: [new Date(startTime).getTime() / 1000, new Date(endTime).getTime() / 1000],
    }).then((res) => {
        state.orderStatisticsChart = res.data
        initOrderStatisticsChart()
    })
}
const orderStatisticsChartRef = ref(null)
const initOrderStatisticsChart = () => {
    state.charts = state.charts.filter((item) => {
        if (item.id === state.orderStatisticsChartId) {
            item.dispose()
            return false
        }
        return true
    })
    const orderStatisticsChartInstance = echarts.init(orderStatisticsChartRef.value)
    const orderStatisticsChartOption = {
        xAxis: {
            type: 'category',
            data: [] as string[],
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: true,
            },
            axisTick: {
                show: true,
            },
        },
        legend: {
            data: [] as string[],
            textStyle: {
                color: '#73767a',
            },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
            },
        },
        series: [] as anyObj[],
        toolbox: {
            show: true,
            feature: {
                magicType: { show: true, type: ['line', 'bar'], title: { line: '折线图', bar: '柱状图' } },
                saveAsImage: { show: true, title: '保存为图片' },
            },
        },
    }

    const orderData = state.orderStatisticsChart
    orderStatisticsChartOption.xAxis.data = orderData.map((item: orderChartItem) => {
        return item.time
    })
    orderStatisticsChartOption.legend.data.push('订单量', '销售额')
    orderStatisticsChartOption.series.push(
        {
            name: '订单量',
            type: 'bar',
            smooth: true,
            data: orderData.map((item: orderChartItem) => {
                return item.total
            }),
            itemStyle: {
                color: '#5470c6', // 深蓝色
            },
            tooltip: {
                valueFormatter: (value: number) => value + '单',
            },
        },
        {
            name: '销售额',
            type: 'line',
            smooth: true,
            areaStyle: {
                opacity: 0.5, // 设置透明度
            },
            data: orderData.map((item: orderChartItem) => {
                return item.totalSale
            }),
            tooltip: {
                valueFormatter: (value: number) => value + '元',
            },
        }
    )

    orderStatisticsChartInstance.setOption(orderStatisticsChartOption)
    state.charts.push(orderStatisticsChartInstance)
    state.orderStatisticsChartId = orderStatisticsChartInstance.getId()
}

const userStatisticsChartTimeRange = ref([])
const onChangeUserStatisticsChartTime = (value: string[]) => {
    if (!value) return
    const [startTime, endTime] = value
    getStatisticsChart({
        type: 'user',
        range: [new Date(startTime).getTime() / 1000, new Date(endTime).getTime() / 1000],
    }).then((res) => {
        state.userStatisticsChart = res.data
        inituserStatisticsChart()
    })
}
const userStatisticsChartRef = ref(null)
const inituserStatisticsChart = () => {
    state.charts = state.charts.filter((item) => {
        if (item.id === state.userStatisticsChartId) {
            item.dispose()
            return false
        }
        return true
    })

    const userStatisticsChartInstance = echarts.init(userStatisticsChartRef.value)

    const option = {
        xAxis: {
            type: 'category',
            data: [] as string[],
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: false,
            },
            axisTick: {
                show: false,
            },
        },
        legend: {
            data: [] as string[],
            textStyle: {
                color: '#73767a',
            },
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'line',
            },
        },
        series: [] as anyObj[],
        toolbox: {
            show: true,
            feature: {
                magicType: { show: true, type: ['line', 'bar'], title: { line: '折线图', bar: '柱状图' } },
                saveAsImage: { show: true, title: '保存为图片' },
            },
        },
    }

    //统计图表数据
    const userData = state.userStatisticsChart

    option.xAxis.data = userData.map((item: userChartItem) => {
        return item.time
    })

    option.series.push({
        name: '注册数',
        type: 'line',
        smooth: true,
        areaStyle: {
            color: '#c7e1ff',
        },
        data: userData.map((item: userChartItem) => {
            return item.total
        }),
        tooltip: {
            valueFormatter: (value: number) => value + '人',
        },
    })

    userStatisticsChartInstance.setOption(option)
    state.charts.push(userStatisticsChartInstance)
    state.userStatisticsChartId = userStatisticsChartInstance.getId()
}

const userConsumeRatioChartRef = ref(null)
const initUserConsumeRatioData = () => {
    const userConsumeRatioChart = echarts.init(userConsumeRatioChartRef.value)

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 20,
            top: 20,
            bottom: 20,
            data: state.userConsumeRatioData.map((item) => item.name),
            textStyle: {
                color: '#73767a',
            },
        },
        series: [
            {
                name: '用户消费金额',
                type: 'pie',
                data: state.userConsumeRatioData,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                },
            },
        ],
    }

    userConsumeRatioChart.setOption(option)
    state.charts.push(userConsumeRatioChart)
}

const echartsResize = () => {
    nextTick(() => {
        for (const key in state.charts) {
            state.charts[key].resize()
        }
    })
}

const onChangeWorkState = () => {
    const time = parseInt((new Date().getTime() / 1000).toString())
    const workingTime = Local.get(WORKING_TIME)
    if (state.pauseWork) {
        // 继续工作
        workingTime.pauseTime += time - workingTime.startPauseTime
        workingTime.startPauseTime = 0
        Local.set(WORKING_TIME, workingTime)
        state.pauseWork = false
        startWork()
    } else {
        // 暂停工作
        workingTime.startPauseTime = time
        Local.set(WORKING_TIME, workingTime)
        clearInterval(workTimer)
        state.pauseWork = true
    }
}

const startWork = () => {
    const workingTime = Local.get(WORKING_TIME) || { date: '', startTime: 0, pauseTime: 0, startPauseTime: 0 }
    const currentDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
    const time = parseInt((new Date().getTime() / 1000).toString())

    if (workingTime.date != currentDate) {
        workingTime.date = currentDate
        workingTime.startTime = time
        workingTime.pauseTime = workingTime.startPauseTime = 0
        Local.set(WORKING_TIME, workingTime)
    }

    let startPauseTime = 0
    if (workingTime.startPauseTime <= 0) {
        state.pauseWork = false
        startPauseTime = 0
    } else {
        state.pauseWork = true
        startPauseTime = time - workingTime.startPauseTime // 已暂停时间
    }

    let workingSeconds = time - workingTime.startTime - workingTime.pauseTime - startPauseTime

    state.workingTimeFormat = formatSeconds(workingSeconds)
    if (!state.pauseWork) {
        workTimer = window.setInterval(() => {
            workingSeconds++
            state.workingTimeFormat = formatSeconds(workingSeconds)
        }, 1000)
    }
}

const formatSeconds = (seconds: number) => {
    var secondTime = 0 // 秒
    var minuteTime = 0 // 分
    var hourTime = 0 // 小时
    var dayTime = 0 // 天
    var result = ''

    if (seconds < 60) {
        secondTime = seconds
    } else {
        // 获取分钟，除以60取整数，得到整数分钟
        minuteTime = Math.floor(seconds / 60)
        // 获取秒数，秒数取佘，得到整数秒数
        secondTime = Math.floor(seconds % 60)
        // 如果分钟大于60，将分钟转换成小时
        if (minuteTime >= 60) {
            // 获取小时，获取分钟除以60，得到整数小时
            hourTime = Math.floor(minuteTime / 60)
            // 获取小时后取佘的分，获取分钟除以60取佘的分
            minuteTime = Math.floor(minuteTime % 60)
            if (hourTime >= 24) {
                // 获取天数， 获取小时除以24，得到整数天
                dayTime = Math.floor(hourTime / 24)
                // 获取小时后取余小时，获取分钟除以24取余的分；
                hourTime = Math.floor(hourTime % 24)
            }
        }
    }

    result =
        hourTime +
        t('shop.dashboard.hour') +
        ((minuteTime >= 10 ? minuteTime : '0' + minuteTime) + t('shop.dashboard.minute')) +
        ((secondTime >= 10 ? secondTime : '0' + secondTime) + t('shop.dashboard.second'))
    if (dayTime > 0) {
        result = dayTime + t('shop.dashboard.day') + result
    }
    return result
}

onActivated(() => {
    echartsResize()
})

onMounted(() => {
    startWork()
    useEventListener(window, 'resize', echartsResize)
    index().then((res) => {
        state.remark = res.data.remark
        state.boardData = res.data.boardData
        state.orderData = res.data.orderData
        state.orderSaleData = res.data.orderSaleData
        state.userData = res.data.userData
        state.orderStatisticsChart = res.data.orderStatisticsChart
        state.userStatisticsChart = res.data.userStatisticsChart
        state.userConsumeRatioData = res.data.userConsumeRatioChart
        state.goodsSaleData = res.data.goodsSaleChart
        initOrderStatisticsChart()
        inituserStatisticsChart()
        initUserConsumeRatioData()
        initCountUp()
    })
})

onBeforeUpdate(() => {})

onBeforeMount(() => {
    for (const key in state.charts) {
        state.charts[key].dispose()
    }
})

onUnmounted(() => {
    clearInterval(workTimer)
})
watch(
    () => navTabs.state.tabFullScreen,
    () => {
        echartsResize()
    }
)
</script>

<style scoped lang="scss">
.welcome {
    background: #e1eaf9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    padding: 15px 20px !important;
    box-shadow: 0 0 30px 0 rgba(82, 63, 105, 0.05);
    .welcome-img {
        height: 100px;
        margin-right: 10px;
        user-select: none;
    }
    .welcome-title {
        font-size: 1.5rem;
        line-height: 30px;
        color: var(--ba-color-primary-light);
    }
    .welcome-note {
        padding-top: 6px;
        font-size: 20px;
        color: var(--el-text-color-primary);
    }
}
.working {
    height: 130px;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    height: 100%;
    position: relative;
    &:hover {
        .working-coffee {
            -webkit-transform: translateY(-4px) scale(1.02);
            -moz-transform: translateY(-4px) scale(1.02);
            -ms-transform: translateY(-4px) scale(1.02);
            -o-transform: translateY(-4px) scale(1.02);
            transform: translateY(-4px) scale(1.02);
            z-index: 999;
        }
    }
    .working-coffee {
        transition: all 0.3s ease;
        width: 80px;
    }
    .working-text {
        display: block;
        width: 100%;
        font-size: 15px;
        text-align: center;
        color: var(--el-text-color-primary);
    }
    .working-opt {
        position: absolute;
        top: -40px;
        right: 10px;
        background-color: rgba($color: #000000, $alpha: 0.3);
        padding: 10px 20px;
        border-radius: 20px;
        color: var(--ba-bg-color-overlay);
        transition: all 0.3s ease;
        cursor: pointer;
        opacity: 0;
        z-index: 999;
        &:active {
            background-color: rgba($color: #000000, $alpha: 0.6);
        }
    }
    &:hover {
        .working-opt {
            opacity: 1;
            top: 0;
        }
        .working-done {
            opacity: 1;
            top: 50px;
        }
    }
}
.small-panel-box {
    margin-top: 20px;
}
.small-panel {
    background-color: #e9edf2;
    border-radius: var(--el-border-radius-base);
    padding: 20px;
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .small-panel-title {
        color: #92969a;
        font-size: 15px;
    }
    .small-panel-title-right {
        display: flex;
        flex-direction: row-reverse;
        color: #92969a;
        margin-top: -20px;
    }
    .small-panel-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 15px;
        color: #2c3f5d;
        .content-left {
            font-size: 28px;
            display: flex;
            align-items: center;
            .icon {
                margin-right: 5px;
            }
            span {
                display: inline-block;
                vertical-align: middle;
                font-size: 26px;
            }
        }
        .content-right {
            font-size: 16px;
            margin-left: auto;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .color-success {
            color: var(--el-color-success);
        }
        .color-warning {
            color: var(--el-color-warning);
        }
        .color-danger {
            color: var(--el-color-danger);
        }
        .color-info {
            color: var(--el-text-color-secondary);
        }
    }
}
.growth-chart {
    margin-bottom: 20px;
}

.order-statistics-chart {
    height: 300px;
}
.user-statistics-chart {
    height: 260px;
}
.user-consume-ratio-chart {
    height: 200px;
}
.goods-sale-rank-chart {
    height: 200px;
}

@media screen and (max-width: 425px) {
    .welcome-img {
        display: none;
    }
}
@media screen and (max-width: 1200px) {
    .lg-mb-20 {
        margin-bottom: 20px;
    }
}
html.dark {
    .welcome {
        background-color: var(--ba-bg-color-overlay);
    }
    .small-panel {
        background-color: var(--ba-bg-color-overlay);
        .small-panel-content {
            color: var(--el-text-color-regular);
        }
    }
    .new-user-item {
        .new-user-base {
            color: var(--el-text-color-regular);
        }
    }
}

.statistic-chart-header {
    display: flex;
    align-items: center;
}
.statistic-chart-header > div:first-child {
    display: flex;
    align-items: center;
}
.statistic-chart-header > div:first-child > span {
    margin-left: 10px;
}
.statistic-chart-header .el-select {
    margin-left: 20px;
    width: 100px;
}

.green {
    color: var(--el-color-success);
}
.red {
    color: var(--el-color-error);
}

.content-bottom {
    font-size: 14px;
    margin-top: 10px;
    color: #92969a;
    min-height: 30px;
    margin-bottom: -10px;
}
.compare {
    display: flex;
    align-items: flex-end;
}
.compare-text {
    margin-left: 5px;
    font-weight: bold;
}
.link-block {
    background-color: #e9edf2;
    cursor: pointer;
    text-decoration: none;
}
.link-block:hover {
    background-color: #e9edf2;
}
</style>
